package com.qingyun.quartz.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qingyun.shop.domain.TiktokCoupon;
import com.qingyun.shop.domain.TiktokCouponDraw;
import com.qingyun.shop.service.ITiktokCouponDrawService;
import com.qingyun.shop.service.ITiktokCouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 优惠券相关的定时任务
 */
@Component("couponTask")
public class CouponTask {

	@Autowired
    private ITiktokCouponDrawService couponDrawService;
	@Autowired
    private ITiktokCouponService couponService;

    @Autowired
    DataSourceTransactionManager dataSourceTransactionManager;
    @Autowired
    TransactionDefinition transactionDefinition;

    /**
     * 定时查询用户领取的优惠券，将过了有效期未使用的券状态改成`已过期`
     */
    @Transactional(rollbackFor = Exception.class)
    public void queryOutmodedCouponDraw() {
        LambdaQueryWrapper<TiktokCouponDraw> lqw = Wrappers.lambdaQuery();
        lqw.eq(TiktokCouponDraw::getUseStatus, 0);
        lqw.le(TiktokCouponDraw::getEndDate,new Date());
        List<TiktokCouponDraw> tiktokCouponDraws = couponDrawService.list(lqw);
        tiktokCouponDraws.forEach(c ->c.setUseStatus(2));
		couponDrawService.updateBatchById(tiktokCouponDraws);
    }

    /**
     * 定时查询商户下的优惠券，过了有效期，将状态改为 已过期
     */
    @Transactional(rollbackFor = Exception.class)
    public void queryOutmodedCoupon() {
        LambdaQueryWrapper<TiktokCoupon> lqw = Wrappers.lambdaQuery();
        lqw.ne(TiktokCoupon::getStatus, 2);
        lqw.le(TiktokCoupon::getEndTime,new Date());
        List<TiktokCoupon> tiktokCoupons = couponService.list(lqw);
        tiktokCoupons.forEach(c -> c.setStatus(2));
        couponService.updateBatchById(tiktokCoupons);
    }
}
